//
//  UIView+ZZExtension.m
//  BabyDiscern
//
//  Created by mac on 2019/5/6.
//  Copyright © 2019 mac. All rights reserved.
//

#import "UIView+LFZExtension.h"

@implementation UIView (ZZExtension)

- (void)setSize:(CGSize)size
{
    CGRect frame = self.frame;
    frame.size = size;
    self.frame = frame;
}

- (CGSize)size
{
    return self.frame.size;
}

- (void)setWidth:(CGFloat)width
{
    CGRect frame = self.frame;
    frame.size.width = width;
    self.frame = frame;
}

- (void)setHeight:(CGFloat)height
{
    CGRect frame = self.frame;
    frame.size.height = height;
    self.frame = frame;
}

- (void)setX:(CGFloat)x
{
    CGRect frame = self.frame;
    frame.origin.x = x;
    self.frame = frame;
}

- (void)setY:(CGFloat)y
{
    CGRect frame = self.frame;
    frame.origin.y = y;
    self.frame = frame;
}

- (void)setCenterX:(CGFloat)centerX
{
    CGPoint center = self.center;
    center.x = centerX;
    self.center = center;
}

- (void)setCenterY:(CGFloat)centerY
{
    CGPoint center = self.center;
    center.y = centerY;
    self.center = center;
}

- (void)setTop:(CGFloat)top
{
    CGRect frame = self.frame;
    frame.origin.y = top;
    self.frame = frame;
}

- (void)setBottom:(CGFloat)bottom {
    
    CGFloat top = bottom - self.frame.size.height;
    CGRect frame = self.frame;
    frame.origin.y = top;
    self.frame = frame;
}

- (void)setLeft:(CGFloat)left {
    CGRect frame = self.frame;
    frame.origin.x = left;
    self.frame = frame;
}

- (void)setRight:(CGFloat)right {
 
    CGFloat left = right - self.frame.size.width;
    CGRect frame = self.frame;
    frame.origin.x = left;
    self.frame = frame;
}

- (CGFloat)centerY
{
    return self.center.y;
}

- (CGFloat)centerX
{
    return self.center.x;
}

- (CGFloat)width
{
    return self.frame.size.width;
}

- (CGFloat)height
{
    return self.frame.size.height;
}

- (CGFloat)x
{
    return self.frame.origin.x;
}

- (CGFloat)y
{
    return self.frame.origin.y;
}

- (CGFloat)top {
    return self.frame.origin.y;
}

- (CGFloat)bottom {
    return self.frame.origin.y + self.frame.size.height;
}

- (CGFloat)left {
    return self.frame.origin.x;
}

- (CGFloat)right {
    return self.frame.origin.x + self.frame.size.width;
}

/// 获取 LaunchScreenView
+(nullable UIView *)getLaunchScreenView
{
    UIView *launchView = nil;
    @try {
        UIViewController *viewController = [[UIStoryboard storyboardWithName:@"LaunchScreen" bundle:nil] instantiateViewControllerWithIdentifier:@"LaunchScreen"];
        launchView = viewController.view;
    }@catch (NSException *exception) {
        
    }
    // 结果处理
    return launchView;
}

/// 颜色转图片
+ (UIImage *)imageFromColor:(UIColor *)color scaleToSize:(CGSize)size
{
    if (!color) return nil;
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

/// 裁圆角
-(void)circleView
{
    [self circleViewByRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomLeft | UIRectCornerBottomRight];
}

-(void)circleViewByCornerRadii:(CGSize)cornerRadii
{
    [self circleViewByRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:cornerRadii];
}

-(void)circleViewByRoundingCorners:(UIRectCorner)corners
{
    [self circleViewByRoundingCorners:corners cornerRadii:CGSizeMake(self.height * 0.5, self.height * 0.5)];
}

-(void)circleViewByRoundingCorners:(UIRectCorner)corners cornerRadii:(CGSize)cornerRadii
{
    UIBezierPath *teacherPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:cornerRadii];
    CAShapeLayer *teacherBtnLayer = [[CAShapeLayer alloc] init];
    teacherBtnLayer.frame = self.bounds;
    teacherBtnLayer.path = teacherPath.CGPath;
    self.layer.mask = teacherBtnLayer;
}

/**
 * 裁剪身份证图片
 * @param imageView 相机展示的视图
 * @param cutView 裁剪框视图
 * @retrun 裁剪后的图片
 */
+(UIImage *)selectImage:(UIImage *)image andImageView:(UIView *)imageView andCutView:(UIView *)cutView
{
    CGImageRef cgRef = image.CGImage;
    
    // 实际照片大小与屏幕大小之比
    CGFloat widthScale = image.size.width / imageView.size.width;
    CGFloat heightScale = image.size.height / imageView.size.height;
    
    //我们要裁剪出实际边框内的图片，但是实际的照片我们看见的屏幕上的图片，size是不一样
    CGFloat x = (imageView.size.width - cutView.width) * 0.5 * widthScale;
    CGFloat y = (imageView.size.height - cutView.height) * 0.5 * heightScale;
    CGFloat width = cutView.size.width * widthScale;
    CGFloat height = cutView.size.height * heightScale;
    
    CGRect r = CGRectMake(x, y, width, height);
    
    CGImageRef imageRef = CGImageCreateWithImageInRect(cgRef, r);
    
    return [UIImage imageWithCGImage:imageRef];
}

+ (NSString *)getTextSuccessWithResult:(id)result {
    NSMutableString *message = [NSMutableString string];
    if (result == nil) {
        return message.copy;
    }
    if ((result[@"words_result"]) == nil) {
        return message.copy;
    }
    
    if([result[@"words_result"] isKindOfClass:[NSDictionary class]]){
        [result[@"words_result"] enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            if([obj isKindOfClass:[NSDictionary class]] && [obj objectForKey:@"words"]){
                [message appendFormat:@"%@: %@\n", key, obj[@"words"]];
            }else{
                [message appendFormat:@"%@: %@\n", key, obj];
            }
        }];
    }else if([result[@"words_result"] isKindOfClass:[NSArray class]]){
        for(NSDictionary *obj in result[@"words_result"]){
            if([obj isKindOfClass:[NSDictionary class]] && [obj objectForKey:@"words"]){
                [message appendFormat:@"%@\n", obj[@"words"]];
            }else{
                [message appendFormat:@"%@\n", obj];
            }
        }
    }
    return message.copy;
}

+(NSString *)contentTypeForImageData:(NSData *)data {
    uint8_t c;
    [data getBytes:&c length:1];
    
    switch (c) {
        case 0xFF:
            return @"jpg";
        case 0x89:
            return @"png";
        case 0x47:
            return @"gif";
        case 0x49:
        case 0x4D:
            return @"tiff";
        case 0x52:
            if ([data length] < 12) {
                return nil;
            }
            
            NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
                return @"webp";
            }
            return @"未判断出来";
    }
    return @"未判断出来";
}

+ (NSString *)urlEncodeStr:(NSString *)input
{
    NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)input, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8));
    
    return encodedString;
}



//获得当前活动窗口的根视图
+ (UIViewController *)findCurrentShowingViewController
{
    UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *currentShowingVC = [self findCurrentShowingViewControllerFrom:vc];
    return currentShowingVC;
}

// 注意考虑几种特殊情况：①A present B, B present C，参数vc为A时候的情况
/* 完整的描述请参见文件头部 */
+ (UIViewController *)findCurrentShowingViewControllerFrom:(UIViewController *)vc
{
    //方法1：递归方法 Recursive method
    UIViewController *currentShowingVC;
    if ([vc presentedViewController]) { //注要优先判断vc是否有弹出其他视图，如有则当前显示的视图肯定是在那上面
        // 当前视图是被presented出来的
        UIViewController *nextRootVC = [vc presentedViewController];
        currentShowingVC = [self findCurrentShowingViewControllerFrom:nextRootVC];
        
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        UIViewController *nextRootVC = [(UITabBarController *)vc selectedViewController];
        currentShowingVC = [self findCurrentShowingViewControllerFrom:nextRootVC];
        
    } else if ([vc isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController
        UIViewController *nextRootVC = [(UINavigationController *)vc visibleViewController];
        currentShowingVC = [self findCurrentShowingViewControllerFrom:nextRootVC];
        
    } else {
        // 根视图为非导航类
        currentShowingVC = vc;
    }
    
    return currentShowingVC;
}

//添加单边阴影
//shadowColor 阴影颜色
//shadowOpacity 阴影透明度，默认0
//shadowRadius 阴影半径，默认3
//shadowPathType 阴影加边类型 0 上边 1下边 2左边 3右边 4左右 5上下 6 上和左右 7 下和左右
//shadowPathWidth 阴影路径宽度
- (void)viewShadowPathWithColor:(UIColor *)shadowColor shadowOpacity:(CGFloat)shadowOpacity shadowRadius:(CGFloat)shadowRadius shadowPathType:(NSInteger)shadowPathType shadowPathWidth:(CGFloat)shadowPathWidth {
    
    self.layer.masksToBounds = NO;//必须要等于NO否则会把阴影切割隐藏掉
    self.layer.shadowColor = shadowColor.CGColor;// 阴影颜色
    self.layer.shadowOpacity = shadowOpacity;// 阴影透明度，默认0
    self.layer.shadowOffset = CGSizeZero;//shadowOffset阴影偏移，默认(0, -3),这个跟shadowRadius配合使用
    self.layer.shadowRadius = shadowRadius;//阴影半径，默认3
    CGRect shadowRect = CGRectZero;
    CGFloat originX,originY,sizeWith,sizeHeight;
    originX = 0;
    originY = 0;
    sizeWith = self.bounds.size.width;
    sizeHeight = self.bounds.size.height;
    
    if (shadowPathType == 0) {
        shadowRect = CGRectMake(originX, originY-shadowPathWidth/2, sizeWith, shadowPathWidth);
    }else if (shadowPathType == 1){
        shadowRect = CGRectMake(originY, sizeHeight-shadowPathWidth/2, sizeWith, shadowPathWidth);
    }else if (shadowPathType == 2){
        shadowRect = CGRectMake(originX-shadowPathWidth/2, originY, shadowPathWidth, sizeHeight);
    }else if (shadowPathType == 3){
        shadowRect = CGRectMake(sizeWith-shadowPathWidth/2, originY, shadowPathWidth, sizeHeight);
    }else if (shadowPathType == 4){
        shadowRect = CGRectMake(originX-shadowPathWidth/2, originY, sizeWith+shadowPathWidth, sizeHeight);
    } else if (shadowPathType == 5){
        shadowRect = CGRectMake(originX, originY - shadowPathWidth/2, sizeWith, sizeHeight + shadowPathWidth);
    } else if (shadowPathType == 6){
        shadowRect = CGRectMake(originX-shadowPathWidth/2, originY-shadowPathWidth/2, sizeWith+shadowPathWidth, sizeHeight);
    } else if (shadowPathType == 7){
        shadowRect = CGRectMake(originX-shadowPathWidth/2, originY-shadowPathWidth/2, sizeWith+shadowPathWidth, sizeHeight+shadowPathWidth);
    }
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRect:shadowRect];
    self.layer.shadowPath = bezierPath.CGPath;//阴影路径
}

@end
